/* eslint-disable no-shadow */
/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Button, Popconfirm, Form, Modal, Input, InputNumber, Row, Col, message, Spin } from 'antd';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import StandardTable from '@/components/StandardTable';
import styles from './style.less';

const FormItem = Form.Item;
const FormModal = Form.create()(props => {
  const {
    form: { getFieldDecorator, validateFields },
    visible,
    handleCancel,
    handleOk,
    record,
  } = props;
  const handleModalOk = () => {
    validateFields((err, values) => {
      if (err) {
        return;
      }
      const params = {
        ...values,
        ...{
          type: record.source == 1 ? 1 : 0,
          id: record.id,
          status: record.status,
        },
      };
      handleOk(params);
    });
  };
  const title =
    record.source == 0 ? '添加计价方案' : record.source == 1 ? '编辑计价方案' : '查看计价方案';
  const isLook = record.source == 2;
  return (
    <Modal
      destroyOnClose
      title={title}
      visible={visible}
      onOk={handleModalOk}
      onCancel={() => handleCancel()}
      footer={
        isLook ? (
          <Button key="back" onClick={handleCancel}>
            取消
          </Button>
        ) : (
          [
            <Button key="back" onClick={handleCancel}>
              取消
            </Button>,
            <Button key="front" type="primary" onClick={handleModalOk}>
              确定
            </Button>,
          ]
        )
      }
      centered
    >
      <FormItem
        labelCol={{ span: 4 }}
        colon={false}
        wrapperCol={{ span: 10 }}
        label="方案名称"
        className="price"
      >
        {isLook ? (
          <span className="ant-form-text" style={{ color: '#f00', marginLeft: '-90px' }}>
            {record.name}
          </span>
        ) : (
          getFieldDecorator('name', {
            initialValue: record.name,
            rules: [
              {
                required: true,
                message: '方案名称不能为空',
              },
              {
                max: 10,
                message: '方案名称最多10个字',
              },
            ],
            validateTrigger: 'onChange',
          })(<Input placeholder="请输入方案名称" />)
        )}
      </FormItem>
      <p>配送费=基础费用+重量费用</p>
      <div style={{ background: '#efefef', padding: '15px 15px 0', marginBottom: '15px' }}>
        <p>基础费用</p>
        <Row gutter={8}>
          <Col className="flex-row price" span={14}>
            <FormItem
              labelCol={{ span: 16 }}
              colon={false}
              wrapperCol={{ span: 6 }}
              label="起步配送公里数<="
            >
              {isLook ? (
                <span className="ant-form-text">{record.basis_km}</span>
              ) : (
                getFieldDecorator('basis_km', {
                  initialValue: record.basis_km,
                  rules: [
                    {
                      required: true,
                      message: '请输入起步配送公里数',
                    },
                  ],
                })(<InputNumber max={99.9} min={0.1} />)
              )}
            </FormItem>
            <span>公里</span>
          </Col>
          <Col className="flex-row price" span={10}>
            <FormItem
              labelCol={{ span: 13 }}
              colon={false}
              wrapperCol={{ span: 9 }}
              label="配送费="
            >
              {isLook ? (
                <span className="ant-form-text">{record.basis_fee}</span>
              ) : (
                getFieldDecorator('basis_fee', {
                  initialValue: record.basis_fee,
                  rules: [
                    {
                      required: true,
                      message: '请输入配送费',
                    },
                  ],
                })(<InputNumber max={99.9} min={0.1} />)
              )}
            </FormItem>
            <span>元</span>
          </Col>
        </Row>
        <Row>
          <Col className="flex-row price" span={16}>
            <FormItem
              labelCol={{ span: 16 }}
              colon={false}
              wrapperCol={{ span: 6 }}
              label="超过起步配送公里数"
            >
              {isLook ? (
                <span className="ant-form-text">{record.over_basis_km}</span>
              ) : (
                getFieldDecorator('over_basis_km', {
                  initialValue: record.over_basis_km,
                  rules: [
                    {
                      required: true,
                      message: '请输入配送费',
                    },
                  ],
                })(<InputNumber max={99.9} min={0.1} />)
              )}
            </FormItem>
            <span style={{ minWidth: '80px' }}>元/公里</span>
          </Col>
        </Row>
      </div>
      <div style={{ background: '#efefef', padding: '15px 15px 0' }}>
        <p>重量计费</p>
        <Row gutter={8}>
          <Col className="flex-row price" span={12}>
            <FormItem
              labelCol={{ span: 14 }}
              colon={false}
              wrapperCol={{ span: 8 }}
              label="起步重量<="
            >
              {isLook ? (
                <span className="ant-form-text">{record.basis_weight}</span>
              ) : (
                getFieldDecorator('basis_weight', {
                  initialValue: record.basis_weight,
                  rules: [
                    {
                      required: true,
                      message: '请输入起步重量',
                    },
                  ],
                })(<InputNumber max={99.9} min={0.1} />)
              )}
            </FormItem>
            <span>千克</span>
          </Col>
          <Col className="flex-row price" span={10}>
            <span>不超过起步重量不计费</span>
          </Col>
        </Row>
        <Row>
          <Col className="flex-row price" span={14}>
            <FormItem
              labelCol={{ span: 14 }}
              colon={false}
              wrapperCol={{ span: 8 }}
              label="超过起步重量"
            >
              {isLook ? (
                <span className="ant-form-text">{record.over_basis_weight}</span>
              ) : (
                getFieldDecorator('over_basis_weight', {
                  initialValue: record.over_basis_weight,
                  rules: [
                    {
                      required: true,
                      message: '请输入超过起步重量',
                    },
                  ],
                })(<InputNumber max={99.9} min={0.1} />)
              )}
            </FormItem>
            <span style={{ minWidth: '80px' }}>元/千克</span>
          </Col>
        </Row>
      </div>
    </Modal>
  );
});

@connect(({ valuation, loading }) => ({
  valuation,
  tableLoading: loading.effects['valuation/getValuationList'],
  changeLoading: loading.effects['valuation/changeValuation'],
  deleteLoading: loading.effects['valuation/deleteValuation'],
}))
export default class Valuation extends PureComponent {
  state = {
    visible: false,
    record: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'valuation/getValuationList',
    });
  }

  changeStatus = record => {
    const { dispatch } = this.props;
    this.setState({
      currentId: record.id,
    });
    dispatch({
      type: 'valuation/changeValuation',
      payload: {
        id: record.id,
        switch: record.status == '1' ? 'OFF' : 'ON',
      },
    });
  };

  deleteValuation = record => {
    const { dispatch } = this.props;
    this.setState({
      currentId: record.id,
    });
    dispatch({
      type: 'valuation/deleteValuation',
      payload: {
        id: record.id,
      },
    });
  };

  openModal = (record, source) => {
    this.setState({
      visible: true,
      record: {
        ...record,
        source,
      },
    });
  };

  handleOk = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'valuation/saveValuation',
      payload: {
        ...values,
      },
      callback: (res, msg) => {
        if (res == 0) {
          dispatch({
            type: 'valuation/getValuationList',
          });
          this.handleCancel();
        } else {
          message.error(msg);
        }
      },
    });
  };

  handleCancel = () => {
    this.setState({
      visible: false,
      record: {},
    });
  };

  render() {
    const {
      valuation: { valuationList },
      tableLoading,
      changeLoading,
      deleteLoading,
    } = this.props;
    const { visible, record, currentId } = this.state;
    const columns = [
      {
        title: '方案名称',
        dataIndex: 'name',
      },
      {
        title: '计价规则',
        render: (text, record) => (
          <div>
            <a
              onClick={() => {
                this.openModal(record, 2);
              }}
            >
              查看
            </a>
          </div>
        ),
      },
      {
        title: '状态',
        dataIndex: 'id',
        render: (text, record) => (
          <div>
            <span style={{ marginRight: '10px' }}>
              {record.status == '1' ? '已开启' : '已关闭'}
            </span>
            {record.status == '1' ? (
              ''
            ) : (
              <Popconfirm
                placement="topLeft"
                title="是否开启该计价方案?"
                onConfirm={() => {
                  this.changeStatus(record);
                }}
                okText="确定"
                cancelText="取消"
              >
                {changeLoading && record.id == currentId ? (
                  <Spin />
                ) : (
                  <a>{record.status == '1' ? '关闭' : '开启'}</a>
                )}
              </Popconfirm>
            )}
          </div>
        ),
      },
      {
        title: '操作',
        render: (text, record) => (
          <div>
            <a
              style={{ marginRight: '30px' }}
              onClick={() => {
                this.openModal(record, 1);
              }}
            >
              编辑
            </a>
            {record.status == '1' ? (
              ''
            ) : (
              <Popconfirm
                placement="topLeft"
                title="是否删除该计价方案？"
                onConfirm={() => {
                  this.deleteValuation(record);
                }}
                okText="确定"
                cancelText="取消"
              >
                {deleteLoading && record.id == currentId ? (
                  <Spin />
                ) : (
                  <a>删除</a>
                )}
              </Popconfirm>
            )}
          </div>
        ),
      },
    ];
    return (
      <PageHeaderLayout title="配送费计价">
        <div className={styles.main}>
          <div className="flex-row justify-between">
            <span>
              配送费计价即配送员每送一个订单，对应核算出配送费收入（同一时间只能启用一种计价方案）
            </span>
            <Button
              type="primary"
              onClick={() => {
                this.openModal({}, 0);
              }}
            >
              添加计价方案
            </Button>
          </div>
          <p />
          <StandardTable
            rowKey="id"
            loading={tableLoading}
            data={valuationList}
            columns={columns}
            onChange={() => {}}
          />
          <FormModal
            record={record}
            visible={visible}
            handleCancel={this.handleCancel}
            handleOk={this.handleOk}
          />
        </div>
      </PageHeaderLayout>
    );
  }
}
